package com.bds.btcdc.util;

import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.springframework.jmx.support.JmxUtils;

import javax.management.MBeanServer;

public class EhcacheUtils {
	private Cache<String, String> cache;


	private EhcacheUtils() {
	}

	private static volatile EhcacheUtils instance = null;

	public static EhcacheUtils getInstance() {
		if (instance == null) {
			synchronized (EhcacheUtils.class) {
				if (instance == null) {
					instance = new EhcacheUtils();
					instance.doStart();
				}
			}
		}
		return instance;
	}

	private void doStart() {
		CacheConfiguration<String, String> cacheConfiguration = CacheConfigurationBuilder
				.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(100))
				.withExpiry(Expirations.timeToLiveExpiration(Duration.of(150, TimeUnit.SECONDS))).build();

		CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("zhishu", cacheConfiguration)
				.build();
		cacheManager.init();
		this.cache = cacheManager.getCache("zhishu", String.class, String.class);


		//获取MBeanServer
		MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
		//将Ehcache的MBean注册到MBeanServer
//		ManagementService.registerMBeans(this.getCacheManager(), JmxUtils.locateMBeanServer(), false, false, false, true);

	}

	public String getCache(String key) {
		return cache.get(key);
	}

	public void putCache(String key, String value) {
		cache.put(key, value);
	}

}
